/**
 * Created by pankaj on 25/10/14.
 */
define(['jquery', 'mustache', 'module/template/homeTemplate'], function ($, Mustache, template) {
    var showComment = function (comments, ul) {
        ul.empty();

        var removeComment = function (commentId, parentId) {
            $.ajax({
                url: '/comment/deleteComment',
                method: 'POST',
                data: {commentId: commentId, updateId: parentId }
                , dataType: "json"
            }).done(function (data) {
                showComment(data, ul);
                // update module factory
            }).fail(function () {
                alert('oops ..');
            });
        };

        var renderComment = function (comment) {
            var li = $(Mustache.render(template['home-update-comment'], comment));
            ul.append(li);
            if (comment.mine) {
                li.find('a.js_remove_comment').click(function () {
                    removeComment(comment.id, comment.parentId);
                });
            } else {
                li.find('a.js_remove_comment').remove();
            }
        };

        if (comments) {
            var top2Comments = comments.splice(0, 2);
            $.each(top2Comments, function (index, comment) {
                renderComment(comment);
            });
            if (comments.length > 0) {
                var showMore = $(Mustache.to_html(template['home-update-comment-show-more'], {'count' : comments.length }) );
                ul.append(showMore);
                showMore.click(function () {
                    $(this).remove();
                    $.each(comments, function (index, comment) {
                        renderComment(comment);
                    });
                });
            }
        }
    };
    return showComment;
});


